package com.funquer.lucene;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;


public class FullTextIndexItemLucene {

	/**
	 * file是设置要索引文件夹位置 和存放索引的位置
	 * @param file
	 * @throws Exception 
	 */
	
	public void createFileIndex(String[] file) throws Exception{
		if(file.length!=2){
			throw new Exception("请设置要索引文件路径和索引存放路径！！！");
		}
		
		File dataDir = new File(file[0]);
		File indexDir = new File(file[1]);
		
		long startTime=new Date().getTime();
		int numIndexed = index(dataDir, indexDir);
		long endTime=new Date().getTime();
		
		System.out.println("总共索引数 "+numIndexed+" 共用时 "+(endTime-startTime)+" 毫秒把文档添加到索引里面去,"+indexDir.getPath());
	}
	
	
	public void createIndex(String saveDir, HashMap<String , String> map) throws Exception{
		
		if(saveDir==null){
			throw new Exception("请设置索引存放路径！！！");
		}
		if(map==null){
			System.out.println("createIndex1中,map为空,没有需要索引的内容!");
			return;
		}
		File indexDir = new File(saveDir);
		createIndex(indexDir, map);
	}
	
	/**
	 * 
	 * indexDir存放索引的位置
	 * map是索引名称如: map.put("title","标题");map.put("body","内容");
	 * @param indexDir
	 * @param map
	 * @throws IOException 
	 * @throws CorruptIndexException 
	 */
	
	public void createIndex(File indexDir , HashMap<String , String> map) throws Exception{
		IndexWriter indexWriter=null;
		Directory directory=null;
		
		if(map==null){
			System.out.println("map为空,没有需要索引的内容!");
			return;
		}
		
		try{
			directory = FSDirectory.open(indexDir);	//将索引存放磁盘
			indexWriter = getIndexWriter(directory);
			
			Set<String> keySet = map.keySet();
			Iterator<String> iterator = keySet.iterator();
			Document document=null;
			while (iterator.hasNext()) {
				String key = iterator.next();
				String value = map.get(key);
				document=new Document();
				
				String name=key, content=value;
				if(key=="contents" || key=="body"){
					document.add(new Field(name, content, Field.Store.YES, Field.Index.ANALYZED));					
				}else{
					document.add(new Field(name, content, Field.Store.YES, Field.Index.NO));
				}
				
//				String title="title",id="id",body="contents";
//				document.add( new Field(body, "nature afshfkjhf很大哦符合法定身份发生纠纷", Field.Store.YES, Field.Index.ANALYZED));
//				document.add( new Field(id, "A005004", Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS));
//				document.add( new Field(title, "I'm title", Field.Store.YES, Field.Index.NO));
				
				indexWriter.addDocument(document);
			}
			
			//optimize()方法是对索引进行优化 
			indexWriter.optimize();   
		}catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(indexWriter!=null){
				indexWriter.close();
			}
		}
	}
	
	public void createIndex(File indexDir , String id, String title, String contents, String name) throws Exception{
		IndexWriter indexWriter=null;
		Directory directory=null;
		
		try{
			directory = FSDirectory.open(indexDir);	//将索引存放磁盘
			indexWriter = getIndexWriter(directory);
			Document document=new Document();
			document.add( new Field("contents", contents, Field.Store.YES, Field.Index.ANALYZED));
			document.add( new Field("id", id, Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS));
			document.add( new Field("title", title, Field.Store.YES, Field.Index.NOT_ANALYZED));
			document.add( new Field("name", name, Field.Store.YES, Field.Index.NOT_ANALYZED));
				
			indexWriter.addDocument(document);
			
			//optimize()方法是对索引进行优化 
			indexWriter.optimize();   
		}catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(indexWriter!=null){
				indexWriter.close();
			}
		}
	}
	
	//生成索引
	public int index(File dataDir, File indexDir) throws IOException{
		int numIndexed=0;
		
		IndexWriter indexWriter=null;
		Directory directory=null;
		
		try{
			/*
			StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT);//分析器
			IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_CURRENT, analyzer);
			iwc.setOpenMode(OpenMode.CREATE_OR_APPEND);
			IndexWriter indexWriter = new IndexWriter(directory, iwc);
			*/
			directory = FSDirectory.open(indexDir);	//将索引存放磁盘
			indexWriter = getIndexWriter(directory);
			
			File[] textFiles = dataDir.listFiles();
			for (int i = 0; i < textFiles.length; i++) {
				System.out.println("File:"+textFiles[i].getCanonicalPath()+"正在被索引...");
				String temp=FileReaderAll(textFiles[i].getCanonicalPath(),"GBK");
				
				Document document = new Document();
				/*
				 * Store.YES – 存储 Store.NO  – 不存储
				 * //Index.ANALYZED – 索引并分词(适用于body, title,
				 */
				Field fieldName=new Field("name",textFiles[i].getName(), Field.Store.YES, Field.Index.NOT_ANALYZED); 
				Field FieldPath=new Field("path",textFiles[i].getPath(),Field.Store.YES,Field.Index.NOT_ANALYZED);
				Field FieldBody=new Field("contents",temp,Field.Store.YES,Field.Index.ANALYZED,Field.TermVector.WITH_POSITIONS_OFFSETS);
				document.add(fieldName);
				document.add(FieldPath);
				document.add(FieldBody);
				indexWriter.addDocument(document);
			}
			
			numIndexed=indexWriter.numDocs();
			//optimize()方法是对索引进行优化 
			indexWriter.optimize();   
		}catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(indexWriter!=null){
				indexWriter.close();
			}
		}
		
		return numIndexed;
	}
	
	public IndexWriter getIndexWriter(Directory directory){
		IndexWriter indexWriter=null;
		try{
			StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT);//分析器
			IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_CURRENT, analyzer);
			iwc.setOpenMode(OpenMode.CREATE_OR_APPEND);
			indexWriter = new IndexWriter(directory, iwc);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return indexWriter;
	}
	
	//读取文件内容
	public String FileReaderAll(String FileName,String charset)throws IOException{
		BufferedReader reader=new BufferedReader(new InputStreamReader(new FileInputStream(FileName),charset));
		String line=new String();
		String temp=new String();
		while ((line=reader.readLine())!=null) {
			temp+=line;
		}
		reader.close();
		return temp;
	}
	
	/*
	 * --------------create index end---------------------------
	 */
	
	public void delete(String index, String id) throws CorruptIndexException, IOException{
		IndexWriter indexWriter=null;
		Directory directory=null;
		File indexDir=new File(index);
		try{
			directory = FSDirectory.open(indexDir);
			indexWriter = getIndexWriter(directory);
			indexWriter.deleteDocuments(new Term("id",id));
			indexWriter.optimize();
		}catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(indexWriter!=null){
				indexWriter.close();
			}
		}
			
	}
	
	public void forceDelete(String index) throws CorruptIndexException, IOException{
		IndexWriter indexWriter=null;
		Directory directory=null;
		File indexDir=new File(index);
		try {
			directory = FSDirectory.open(indexDir);
			indexWriter = getIndexWriter(directory);
			//此时删除的文档并未完全删除，而是存储在回收站中，可以恢复的
			indexWriter.forceMergeDeletes();
		} catch (CorruptIndexException e) {
			e.printStackTrace();
		}finally{
			if (indexWriter!=null) {
				indexWriter.close();
			}
		}
	}
	
	public void update(String index, String id, String title, String contents, String name) throws IOException{
		IndexWriter indexWriter=null;
		Directory directory=null;
		File indexDir=new File(index);
		try {
			directory = FSDirectory.open(indexDir);
			indexWriter = getIndexWriter(directory);
			indexWriter.deleteDocuments(new Term("id",id));
			
			Document document=new Document();
			document.add( new Field("contents", contents, Field.Store.YES, Field.Index.ANALYZED));
			document.add( new Field("id", id, Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS));
			document.add( new Field("title", title, Field.Store.YES, Field.Index.NOT_ANALYZED));
			document.add( new Field("name", name, Field.Store.YES, Field.Index.NOT_ANALYZED));
				
			indexWriter.updateDocument(new Term("id",id), document);
			indexWriter.optimize();
		} catch (CorruptIndexException e) {
			e.printStackTrace();
		}finally{
			if (indexWriter!=null) {
				indexWriter.close();
			}
		}
	}
	
	
	public static void main(String[] args) throws Exception {
//		String [] file = new String[]{"D:\\logs\\source","D:\\logs\\index"};
//		new FullTextIndexItemLucene().createFileIndex(file);
		
//		HashMap<String, String> map=new HashMap<String, String>();
//		map.put("id", "A0071");
//		map.put("title", "grandpa's trunk");
//		map.put("body", "nature fsaaaeeeeeqqqqffffffssssssaaaaaaeeeeetttttttt的");
//		new FullTextIndexItemLucene().createIndex("D:\\logs\\index", map);
		
//		String id="002"; String title="I am title"; String contents="contents contents"; String name="I am name";
//		new FullTextIndexItemLucene().createIndex(new File("D:\\logs\\index"), id, title, contents, name);
		
//		new FullTextIndexItemLucene().delete("D:\\logs\\index", "001");
		
//		String id="002"; String title="I am title aaaa"; String contents="contents contents hihi"; String name="I am name";
//		new FullTextIndexItemLucene().update("D:\\logs\\index", id, title, contents, name);
	}
}
